/*
 * cxml.h
 *
 *  Created on: 2008-10-29
 *      Author: root
 */

#ifndef CXML_H_
#define CXML_H_

#include <assert.h>
#include "tinyxml.h"
#include "../sql/sqlite3.h"
#define IDLENV 16											// id from naming group, 128 bits, not dht nodeid
#define DHTIDLEN 20

class CXML
{
public:
	CXML();
	virtual ~CXML()
	{
	}
	;

	void setTitle(const char *);
	void setType(const char *);
	void setOper(const char *);
	void setNID(const unsigned char *);
	void setTime(int);
	void setReqID(int);
	virtual void formXML(char *)
	{
	}
	const char *getTitle();
	const char *getType();
	const char *getOper();
	const char *getNID();
	int getTime();
	int getReqID();
	virtual void readHead(const char *);
	virtual void readDetail(const char *)
	{
	}
	virtual void formReqSQL(char *)
	{
	}
	virtual void formStoreSQL(char *)
	{
	}
	virtual int query(sqlite3 *)
	{
		return 0;
	}
	virtual int store(sqlite3 *)
	{
		return 0;
	}
	virtual void formCID(unsigned char *)
	{
	}

protected:
	char title[32]; // contextRequest or ContextResponse
	char type[32]; // resourceInfo or linkState
	char oper[32];
	char nid[IDLENV];	// from naming group, not string
	int time;
	int reqId; // requestor ID 仅用作发送请求时，通知对方回复的通道
};

/*
 * the following codes implement the above functions
 */
CXML::CXML()
{
	time = reqId = 0;
}

void CXML::setTitle(const char *titlev)
{
	strcpy(title, titlev);
}

void CXML::setType(const char *typev)
{
	strcpy(type, typev);
}

void CXML::setOper(const char *operation)
{
	strcpy(oper, operation);
}

void CXML::setNID(const unsigned char *nidv)
{
	memcpy(nid, nidv, IDLENV);
}
void CXML::setTime(int timev)
{
	time = timev;
}

void CXML::setReqID(int requestorID)
{
	reqId = requestorID;
}

const char *CXML::getTitle()
{
	return title;
}

const char *CXML::getType()
{
	return type;
}

const char *CXML::getOper()
{
	return oper;
}

const char *CXML::getNID()
{
	return nid;
}

int CXML::getTime()
{
	return time;
}

int CXML::getReqID()
{
	return reqId;
}

//read xml info head, get the common infos about msg title, type, oper, nid
void CXML::readHead(const char *info)
{
	assert(info != NULL);

	TiXmlDocument doc;
	doc.Parse(info);

	TiXmlElement *rootElem;
	TiXmlElement *pElem;
	const char *tmp = NULL;

	rootElem = doc.RootElement();
	if (!rootElem)
	{
		printf("Error in parsing XML string!\n");
		exit(1);
	}

	setTitle(rootElem->Value()); // title
	setType(rootElem->Attribute("msgType")); //msgType

	pElem = rootElem->FirstChildElement("operation"); //oper
	setOper(pElem->GetText());
	tmp = pElem->Attribute("requestorId");
	if (tmp)
		setReqID(atoi(tmp)); // reqid
	pElem = rootElem->FirstChildElement("nodeId"); // nid
	tmp = pElem->GetText();
	if (tmp)
		setNID((const unsigned char *)tmp);
}

#endif /* CXML_H_ */
